﻿using System;
using System.Data;
using System.Data.Linq;

namespace SBRepository.LinqToSql
{
    public class LinqToSqlSession : ISession
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="LinqToSqlSession"/> class.
        /// </summary>
        public LinqToSqlSession(DataContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            Context = context;

#if DEBUG
            Context.Log = new DebuggerWriter();
#endif
        }

        /// <summary>
        /// Gets the database connection.
        /// </summary>
        /// <value>The database connection.</value>
        public IDbConnection Connection
        {
            get
            {
                return Context.Connection;
            }
        }

        /// <summary>
        /// Gets or sets the data context.
        /// </summary>
        /// <value>The data context.</value>
        internal DataContext Context { get; private set; }

        /// <summary>
        /// Commits current session.
        /// </summary>
        public void Commit()
        {
            Context.SubmitChanges();
            Context.ClearCache();
        }

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public void Dispose()
        {
            Context.Dispose();
        }
    }
}
